package alf.mapping.view.activity;
import alf.mapping.dto.maps.Item;
import alf.mapping.dto.maps.Link;
import alf.mapping.dto.maps.NavigationLink;
import alf.mapping.view.Env;
import alf.mapping.view.Util;
import alf.mapping.view.activity.R;
import alf.mapping.view.visuals.EditorEngine;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class LinkEditionActivity extends SimpleAbstractActivity {

	private EditorEngine editor;
	private Item item;
	private Link link;
	private String oldLink;
	private int linkIndex;

	private static final int REQUEST_ITEM_SELECT = 0;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.link_edit);
		editor = EditorEngine.getInstance();
		item = editor.getSelected().get(0).getItem();
		String param = getIntent().getData().getQueryParameter("index");
		linkIndex = Integer.parseInt(param);
		loadLinkData(linkIndex);  
    }

	private void loadLinkData(int index) {
		link = item.getLinks().get(index);
		Util.setText(this, R.id.link_title, link.getTitle());
		String linkText = "";
		if (link.getDestination() != null) {
			linkText  = link.getDestination().toString();
		}
		Util.setText(this, R.id.link_destination, linkText);
		oldLink = linkText;
		Util.setCheck(this, R.id.link_visible, link.isVisible());
		Util.setCheck(this, R.id.link_navigable, link.isNavigable());
		Util.setText(this, R.id.link_style, link.getStyle());
	}

	public void onOk(View v) {
		updateLinkData();
		finish();
	}

	private void updateLinkData() {
		link.setTitle(Util.getText(this, R.id.link_title));

		String newLink = Util.getText(this, R.id.link_destination);
		if (!newLink.equals(oldLink)) {
			NavigationLink parseLink = editor.parseLink(newLink);
			link.setDestination(parseLink);
			Env.toast(this, "new link:" + parseLink);
		}
		link.setVisible(Util.isChecked(this, R.id.link_visible));
		link.setNavigable(Util.isChecked(this, R.id.link_navigable));
		link.setStyle(Util.getText(this, R.id.link_style));
	}

	public void onItemSearch(View v) {
		Intent i = new Intent(this, ItemSelectionActivity.class);
		i.putExtra(Intent.EXTRA_TEXT,  Util.getText(this, R.id.link_destination));
		startActivityForResult(i, REQUEST_ITEM_SELECT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
				case REQUEST_ITEM_SELECT:
					String path = data.getStringExtra(Intent.EXTRA_RETURN_RESULT);
					Util.setText(this, R.id.link_destination, path);
					break;
			}
		}
	}
}
